// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { limit = 50 } = event

  try {
    // 获取排行榜数据，按最高分降序排列
    console.log('查询排行榜数据，限制条数:', limit)
    const rankingResult = await db.collection('scores')
      .orderBy('bestScore', 'desc')
      .limit(limit)
      .get()
    
    console.log('查询到的原始数据:', rankingResult)

    // 获取当前用户的分数和排名
    const currentUserResult = await db.collection('scores').where({
      openid: wxContext.OPENID
    }).get()

    let myRank = 0
    let myBestScore = 0

    if (currentUserResult.data.length > 0) {
      const myScore = currentUserResult.data[0].bestScore
      myBestScore = myScore

      // 计算排名：比我分数高的人数 + 1
      const higherScoresResult = await db.collection('scores').where({
        bestScore: db.command.gt(myScore)
      }).count()

      myRank = higherScoresResult.total + 1
    }

    // 处理排行榜数据，移除敏感信息
    const rankingList = rankingResult.data.map((item, index) => ({
      rank: index + 1,
      nickname: item.nickname,
      avatarUrl: item.avatarUrl,
      score: item.bestScore,
      isCurrentUser: item.openid === wxContext.OPENID
    }))

    console.log('处理后的rankingList:', rankingList)
    console.log('我的排名:', myRank, '我的分数:', myBestScore)

    return {
      success: true,
      rankingList,
      myRank,
      myBestScore,
      total: rankingResult.data.length
    }
  } catch (error) {
    console.error('获取排行榜失败：', error)
    return { success: false, error: error.message }
  }
} 